import http from '@/utils/http'
import axios from 'axios'
import type { 
  ApiResponse, 
  LoginParams, 
  LoginResponse, 
  User,
  Order,
  OrderSearchParams,
  OrderListResponse,
  Vehicle,
  VehicleSearchParams,
  Driver,
  DriverSearchParams,
  Route,
  DashboardStats,
  PageData,
  Invoice,
  InvoiceSearchParams,
  InvoiceListResponse
} from '@/types/api'

// 用户认证相关API
export const authApi = {
  // 登录
  login(params: LoginParams): Promise<ApiResponse<LoginResponse>> {
    return http.post('/auth/login', params)
  },

  // 登出
  logout(): Promise<ApiResponse<void>> {
    return http.post('/auth/logout')
  },

  // 获取用户信息
  getUserInfo(): Promise<ApiResponse<User>> {
    return http.get('/auth/user')
  },

  // 刷新token
  refreshToken(): Promise<ApiResponse<{ token: string }>> {
    return http.post('/auth/refresh')
  }
}

// 网关基础地址配置
// 强制使用8000端口网关地址，不允许环境变量覆盖
const isDev = import.meta.env.DEV
const GATEWAY_BASE = 'http://115.190.179.32:8000'

// 订单管理服务地址配置（网关地址）
// 方式1：通过代理访问（相对路径，main.ts 中已设置 baseURL = '/api'）
const ORDER_READ_BASE = isDev ? '/traceapiread' : `${GATEWAY_BASE}/traceapiread`
const ORDER_WRITE_BASE = isDev ? '/traceapiwrite' : `${GATEWAY_BASE}/traceapiwrite`

// 方式2：直接访问完整URL（同时导出供需要的地方使用）
const ORDER_READ_BASE_DIRECT = `${GATEWAY_BASE}/traceapiread`
const ORDER_WRITE_BASE_DIRECT = `${GATEWAY_BASE}/traceapiwrite`

// 物资读服务（setapiread）
const SET_READ_BASE = isDev ? '/setapiread' : `${GATEWAY_BASE}/setapiread`
// 物资写服务（setapiwrite）
const SET_WRITE_BASE = isDev ? '/setapiwrite' : `${GATEWAY_BASE}/setapiwrite`
// 物料读服务（mateapiread）
const MATE_READ_BASE = isDev ? '/mateapiread' : `${GATEWAY_BASE}/mateapiread`
// 物料写服务（mateapiwrite）
const MATE_WRITE_BASE = isDev ? '/mateapiwrite' : `${GATEWAY_BASE}/mateapiwrite`

// 导出网关地址供其他模块使用
export const GATEWAY_URL = {
  BASE: GATEWAY_BASE,
  // 通过代理访问（推荐用于开发环境）
  TRACE_READ: ORDER_READ_BASE,
  TRACE_WRITE: ORDER_WRITE_BASE,
  // 直接访问完整URL（两种方式都可用）
  TRACE_READ_DIRECT: ORDER_READ_BASE_DIRECT,
  TRACE_WRITE_DIRECT: ORDER_WRITE_BASE_DIRECT,
  SET_READ: SET_READ_BASE,
  SET_WRITE: SET_WRITE_BASE,
  MATE_READ: MATE_READ_BASE,
  MATE_WRITE: MATE_WRITE_BASE
}

// 订单管理API
export const orderApi = {
  // 获取订单列表（读操作 - 保持原样）
  getOrderList: (params: OrderSearchParams) => 
    http.get<OrderListResponse>(`${ORDER_READ_BASE}/api/Order/GetOrderList`, { params }),
  
  // 获取订单详情（读操作 - 保持原样）
  getOrderDetail: (id: number) => 
    http.get<Order>(`${ORDER_READ_BASE}/api/Order/${id}`),
  
  // 创建订单（写操作 - 使用完整网关地址）
  createOrder: (data: Partial<Order>) => 
    http.post<Order>(`http://115.190.179.32:8000/traceapiwrite/api/Order/Create`, data),
  
  // 更新订单（写操作 - 使用完整网关地址）
  updateOrder: (data: Partial<Order>) => 
    http.post<Order>(`http://115.190.179.32:8000/traceapiwrite/api/Order/Update`, data),
  
  // 删除订单（写操作 - 使用完整网关地址）
  deleteOrder: (id: number) => 
    http.post(`http://115.190.179.32:8000/traceapiwrite/api/Order/Delete`, { id, deletedBy: '王大锤' }),
  
  // 分配车辆和司机（写操作 - 使用完整网关地址）
  assignOrder: (id: number, data: { vehicleId: number; driverId: number }) => 
    http.post(`http://115.190.179.32:8000/traceapiwrite/api/Order/${id}/assign`, data),
  
  // 更新订单状态（写操作 - 使用完整网关地址）
  updateOrderStatus: (id: number, status: string) => 
    http.patch(`http://115.190.179.32:8000/traceapiwrite/api/Order/${id}/status`, { status }),
  
  // 导出订单（读操作 - 保持原样）
  exportOrders: (params: {
    Order_number?: string;
    Item_name?: string;
    StartDate?: string;
    EndDate?: string;
    FileName?: string;
  }) => {
    // 使用GET请求并返回blob数据用于文件下载
    return http.get(`${ORDER_READ_BASE}/api/Order/ExportOrders/export`, { 
      params,
      responseType: 'blob'
    })
  }
}

// 车辆管理API
export const vehicleApi = {
  // 获取车辆列表
  getVehicleList(params: VehicleSearchParams): Promise<ApiResponse<PageData<Vehicle>>> {
    return http.get('/vehicles', { params })
  },

  // 获取车辆详情
  getVehicleDetail(id: number): Promise<ApiResponse<Vehicle>> {
    return http.get(`/vehicles/${id}`)
  },

  // 创建车辆
  createVehicle(data: Partial<Vehicle>): Promise<ApiResponse<Vehicle>> {
    return http.post('/vehicles', data)
  },

  // 更新车辆
  updateVehicle(id: number, data: Partial<Vehicle>): Promise<ApiResponse<Vehicle>> {
    return http.put(`/vehicles/${id}`, data)
  },

  // 删除车辆
  deleteVehicle(id: number): Promise<ApiResponse<void>> {
    return http.delete(`/vehicles/${id}`)
  },

  // 获取可用车辆
  getAvailableVehicles(): Promise<ApiResponse<Vehicle[]>> {
    return http.get('/vehicles/available')
  }
}

// 司机管理API
export const driverApi = {
  // 获取司机列表
  getDriverList(params: DriverSearchParams): Promise<ApiResponse<PageData<Driver>>> {
    return http.get('/drivers', { params })
  },

  // 获取司机详情
  getDriverDetail(id: number): Promise<ApiResponse<Driver>> {
    return http.get(`/drivers/${id}`)
  },

  // 创建司机
  createDriver(data: Partial<Driver>): Promise<ApiResponse<Driver>> {
    return http.post('/drivers', data)
  },

  // 更新司机
  updateDriver(id: number, data: Partial<Driver>): Promise<ApiResponse<Driver>> {
    return http.put(`/drivers/${id}`, data)
  },

  // 删除司机
  deleteDriver(id: number): Promise<ApiResponse<void>> {
    return http.delete(`/drivers/${id}`)
  },

  // 获取可用司机
  getAvailableDrivers(): Promise<ApiResponse<Driver[]>> {
    return http.get('/drivers/available')
  }
}

// 路线管理API
export const routeApi = {
  // 获取路线列表
  getRouteList(params: any) {
    return http.get(`${ORDER_READ_BASE}/api/Route/list`, { params })
  },

  // 获取路线详情
  getRouteDetail(id: number) {
    return http.get(`${ORDER_READ_BASE}/api/Route/${id}`)
  },

  // 创建路线
  createRoute(data: any) {
    return http.post(`${ORDER_WRITE_BASE}/api/Route/Create`, data)
  },

  // 更新路线
  updateRoute(data: any) {
    return http.post(`${ORDER_WRITE_BASE}/api/Route/Update`, data)
  },

  // 删除路线
  deleteRoute(id: number, deletedBy: string) {
    return http.post(`${ORDER_WRITE_BASE}/api/Route/Delete`, { id, deletedBy })
  }
}

// 统计数据API
export const statsApi = {
  // 获取仪表板统计数据
  getDashboardStats(): Promise<ApiResponse<DashboardStats>> {
    return http.get('/stats/dashboard')
  },

  // 获取订单统计
  getOrderStats(startDate?: string, endDate?: string): Promise<ApiResponse<any>> {
    return http.get('/stats/orders', { 
      params: { startDate, endDate } 
    })
  },

  // 获取收入统计
  getRevenueStats(period: 'day' | 'week' | 'month' | 'year'): Promise<ApiResponse<any>> {
    return http.get('/stats/revenue', { 
      params: { period } 
    })
  }
}

// 发票管理API
export const invoiceApi = {
  // 获取进项发票列表
  getInboundInvoices(params: InvoiceSearchParams): Promise<ApiResponse<InvoiceListResponse>> {
    return http.get('/api/InboundOutboundInvoice/GetInboundInvoices', { params })
  },

  // 获取销项发票列表
  getOutboundInvoices(params: InvoiceSearchParams): Promise<ApiResponse<InvoiceListResponse>> {
    return http.get('/api/InboundOutboundInvoice/GetOutboundInvoices', { params })
  },

  // 获取发票详情
  getInvoiceDetail(id: number): Promise<ApiResponse<Invoice>> {
    return http.get(`/api/InboundOutboundInvoice/${id}`)
  },

  // 创建发票
  createInvoice(data: Partial<Invoice>): Promise<ApiResponse<Invoice>> {
    return http.post('/api/InboundOutboundInvoice', data)
  },

  // 更新发票
  updateInvoice(id: number, data: Partial<Invoice>): Promise<ApiResponse<Invoice>> {
    return http.put(`/api/InboundOutboundInvoice/${id}`, data)
  },

  // 删除发票
  deleteInvoice(id: number): Promise<ApiResponse<void>> {
    return http.delete(`/api/InboundOutboundInvoice/${id}`)
  },

  // 批量删除发票
  batchDeleteInvoices(ids: number[]): Promise<ApiResponse<void>> {
    return http.post('/api/InboundOutboundInvoice/batchDelete', { ids })
  }
}

// 文件上传API
export const uploadApi = {
  // 上传文件
  uploadFile(file: File): Promise<ApiResponse<{ url: string; filename: string }>> {
    return http.upload('/upload/file', file)
  },

  // 上传头像
  uploadAvatar(file: File): Promise<ApiResponse<{ url: string }>> {
    return http.upload('/upload/avatar', file)
  },

  // 批量上传
  uploadMultiple(files: File[]): Promise<ApiResponse<{ urls: string[] }>> {
    const formData = new FormData()
    files.forEach(file => {
      formData.append('files', file)
    })
    
    return http.post('/upload/multiple', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

// setapiread 读服务常用接口封装
export const setApi = {
  // 显示所有物资统计数据
  getMaterialStatistics() {
    return http.get(`${SET_READ_BASE}/api/MaterialStatistics/show`)
  },

  // 通过ID查询物资领用详情
  getMaterialWithdrawalDetail(id: number) {
    return http.get(`${SET_READ_BASE}/api/MaterialWithdrawal/GetDetail/${id}`)
  },

  // 新增物资采购（示例：供写服务调用）
  addSupplyPurchase(data: any) {
    return http.post(`${SET_WRITE_BASE}/api/SupplyPurchase/AddSupplyPurchase`, data)
  },

  // 更新物资采购（示例：供写服务调用）
  updateSupplyPurchase(data: any) {
    return http.post(`${SET_WRITE_BASE}/api/SupplyPurchase/UpdateSupplyPurchase`, data)
  },

  // ================== 发票（进项）相关（setapiread） ==================
  // 列表
  getInboundInvoices(params: any) {
    return http.getWithResponse(`${SET_READ_BASE}/api/InboundOutboundInvoice/GetInboundInvoices`, { params })
  },
  // 批量删除
  deleteListInboundOutboundInvoice(ids: number[]) {
    return http.post(`${SET_WRITE_BASE}/api/InboundOutboundInvoice/DeleteLsitInboundOutboundInvoice`, { ids })
  },
  // 单条删除
  deleteInboundOutboundInvoice(id: number) {
    return http.post(`${SET_WRITE_BASE}/api/InboundOutboundInvoice/DeleteInboundOutboundInvoice`, { id })
  },
  // 导出Excel
  exportInboundInvoicesToExcel() {
    return http.get(`${SET_READ_BASE}/api/InboundOutboundInvoice/ExportInvoicesToExcel`, { responseType: 'blob' })
  },

  // ================== 发票（销项）相关（feeread/feewrite） ==================
  // 获取销项发票列表
  getOutboundInvoices(params: any) {
    return http.getWithResponse(`${FEE_READ_BASE}/api/InboundOutboundInvoice/GetOutboundInvoices`, { params })
  },
  // 批量删除销项发票
  deleteListOutboundInvoices(ids: number[]) {
    return http.post(`${FEE_WRITE_BASE}/api/InboundOutboundInvoice/DeleteLsitInboundOutboundInvoice`, { ids })
  },
  // 删除单个销项发票
  deleteOutboundInvoice(id: number) {
    return http.post(`${FEE_WRITE_BASE}/api/InboundOutboundInvoice/DeleteInboundOutboundInvoice`, { id })
  },
  // 导出销项发票到Excel
  exportOutboundInvoicesToExcel() {
    return http.get(`${FEE_READ_BASE}/api/InboundOutboundInvoice/ExportInvoicesToExcel`, { responseType: 'blob' })
  },

  // ================== 发票管理相关（进项和销项通用） ==================
  // 添加发票（进项或销项）
  addInboundOutboundInvoice(data: any) {
    return http.post(`${FEE_WRITE_BASE}/api/InboundOutboundInvoice/AddInboundOutboundInvoice`, data)
  },
  // 更新发票
  updateInboundOutboundInvoice(data: any) {
    return http.post(`${FEE_WRITE_BASE}/api/InboundOutboundInvoice/UpdateInboundOutboundInvoice`, data)
  },
  // 获取发票详情
  getInvoiceDetails(id: number) {
    return http.get(`${FEE_READ_BASE}/api/InboundOutboundInvoice/GetInvoiceDetails`, { params: { id } })
  }
}

// mateapiread/mateapiwrite 物料服务封装
export const mateApi = {
  // 物料列表（示例：根据后端定义扩展）
  getMaterials(params?: any) {
    return http.get(`${MATE_READ_BASE}/api/Materials/list`, { params })
  },

  // 物料详情
  getMaterialDetail(id: number) {
    return http.get(`${MATE_READ_BASE}/api/Materials/detail/${id}`)
  },

  // 新增物料
  addMaterial(data: any) {
    return http.post(`${MATE_WRITE_BASE}/api/Materials/add`, data)
  },

  // 更新物料
  updateMaterial(data: any) {
    return http.post(`${MATE_WRITE_BASE}/api/Materials/update`, data)
  },

  // 删除物料
  deleteMaterial(id: number) {
    return http.delete(`${MATE_WRITE_BASE}/api/Materials/delete/${id}`)
  }
}

// 费用管理API
export const feeApi = {
  // ================== 应付费用管理相关 ==================
  // 获取应付费用列表
  getPayableFees(params: any) {
    return http.getWithResponse(`${FEE_READ_BASE}/api/ReceivableFee/GetPayableFees`, { params })
  },

  // 删除单个费用记录
  deleteReceivableFee(id: number) {
    return http.post(`${FEE_WRITE_BASE}/api/ReceivableFee/DeleteReceivableFee`, { id })
  },

  // 批量删除费用记录
  deleteReceivableFeeList(ids: number[]) {
    return http.post(`${FEE_WRITE_BASE}/api/ReceivableFee/DeleteReceivableFeeLsit`, { ids })
  },

  // 获取费用详情
  getFeeDetail(id: number) {
    return http.get(`${FEE_READ_BASE}/api/ReceivableFee/${id}`)
  },

  // 创建费用记录
  createFee(data: any) {
    return http.post(`${FEE_WRITE_BASE}/api/ReceivableFee`, data)
  },

  // 更新费用记录
  updateFee(data: any) {
    return http.put(`${FEE_WRITE_BASE}/api/ReceivableFee`, data)
  },

  // ================== 应收费用管理相关 ==================
  // 获取应收费用列表
  getReceivableFees(params: any) {
    return http.getWithResponse(`${FEE_READ_BASE}/api/ReceivableFee/GetReceivableFees`, { params })
  },

  // ================== 费用管理通用方法 ==================
  // 添加费用记录
  addReceivableFee(data: any) {
    return http.post(`${FEE_WRITE_BASE}/api/ReceivableFee/AddReceivableFee`, data)
  },
  // 更新费用记录
  updateReceivableFee(data: any) {
    return http.post(`${FEE_WRITE_BASE}/api/ReceivableFee/UpdateReceivableFee`, data)
  },
  // 获取费用详情
  getReceivableFeeDetails(id: number) {
    return http.get(`${FEE_READ_BASE}/api/ReceivableFee/GetReceivableFeeDetails`, { params: { id } })
  }
}

// 支付管理API
export const paymentApi = {
  // ================== 支付管理相关 ==================
  // 获取支付列表
  getPayments(params: any) {
    return http.getWithResponse(`${PAYMENT_READ_BASE}/api/Pay`, { params })
  },

  // 删除单个支付记录
  deletePayment(id: number) {
    return http.post(`${PAYMENT_WRITE_BASE}/api/Pay/DeletePaymentManagemen`, { id })
  },

  // 批量删除支付记录
  deletePaymentList(ids: number[]) {
    return http.post(`${PAYMENT_WRITE_BASE}/api/Pay/DeletePaymentManagemenList`, { ids })
  },

  // 获取支付详情
  getPaymentDetail(id: number) {
    return http.get(`${PAYMENT_READ_BASE}/api/Pay/details`, { params: { id } })
  },

  // 创建支付记录
  createPayment(data: any) {
    return http.post(`${PAYMENT_WRITE_BASE}/api/Pay`, data)
  },

  // 更新支付记录
  updatePayment(data: any) {
    return http.put(`${PAYMENT_WRITE_BASE}/api/Pay`, data)
  },

  // 提交审批
  submitApproval(data: any) {
    // 直接调用8000端口完整URL，绕过代理和baseURL
    const url = 'http://115.190.179.32:8000/ExamineEngieWrite/api/ExamineEngie/CreateFirstProcessDetail'
    console.log('API调用URL:', url)
    console.log('API调用数据:', data)
    
    return axios.post(url, data, {
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(response => {
      console.log('API响应成功:', response)
      return response
    }).catch(error => {
      console.error('API调用失败:', error)
      throw error
    })
  },

  // ================== 支付管理通用方法 ==================
  // 添加支付记录
  addPaymentManagemen(data: any) {
    return http.post(`${PAYMENT_WRITE_BASE}/api/Pay/AddPaymentManagemen`, data)
  },
  // 更新支付记录
  updatePaymentManagemen(data: any) {
    return http.post(`${PAYMENT_WRITE_BASE}/api/Pay/UpdatePaymentManagemen`, data)
  },
  // 上传图片
  uploadImage(file: File) {
    const formData = new FormData()
    formData.append('file', file)
    return http.post(`${PAYMENT_WRITE_BASE}/api/Pay/UploadImage`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

// 天气（心知天气 Seniverse）API
// 统一通过本地代理 `/seniverse` 以避免 CORS
const SENIVERSE_KEY = (import.meta as any)?.env?.VITE_SENIVERSE_KEY || 'SgmcySoYOWjd_f1U6'
export const weatherApi = {
  // 实时天气 now.json
  // https://api.seniverse.com/v3/weather/now.json?key=KEY&location=beijing&language=zh-Hans&unit=c
  getNow(params: { location: string; language?: string; unit?: 'c' | 'f'; key?: string }) {
    const { location, language = 'zh-Hans', unit = 'c' } = params
    const key = params.key || SENIVERSE_KEY
    // 直接返回原始响应（非统一 ApiResponse 结构），由调用方自行处理
    return fetch(`/seniverse/v3/weather/now.json?key=${encodeURIComponent(key)}&location=${encodeURIComponent(location)}&language=${encodeURIComponent(language)}&unit=${encodeURIComponent(unit)}`)
      .then(r => r.json())
  }
}

// 服务地址统一通过 Kong 网关
// 环境变量 VITE_KONG_BASE_URL 未提供时，默认 http://115.190.179.32:8000
const KONG_BASE = ((import.meta as any)?.env?.VITE_KONG_BASE_URL || 'http://115.190.179.32:8000') as string
const KB = KONG_BASE.replace(/\/+$/,'')
// 不在 baseURL 后拼 /api，每个服务各自有前缀
// 开发环境使用代理路径，生产环境使用完整URL
const EXAMINE_READ_BASE  = isDev ? '/ExamineEngieRead' : `${KB}/ExamineEngieRead/api`
const EXAMINE_WRITE_BASE = isDev ? '/ExamineEngieWrite' : `${KB}/ExamineEngieWrite/api`
const CARSERV_READ_BASE  = `${KB}/CarServerRead/api`
const CARSERV_WRITE_BASE = `${KB}/CarServerWrite/api`
// 基础信息（车辆管理等）读/写端
const BASICINFO_READ_BASE  = `${KB}/BasicInformationRead/api`
const BASICINFO_WRITE_BASE = `${KB}/BasicInformationWrite/api`

// 费用管理服务地址配置
// 强制使用8000端口网关地址，使用setapiread
const FEE_READ_BASE  = `${GATEWAY_BASE}/setapiread`
const FEE_WRITE_BASE = `${GATEWAY_BASE}/setapiwrite`

// 支付管理服务地址配置
const PAYMENT_READ_BASE  = `${GATEWAY_BASE}/setapiread`
const PAYMENT_WRITE_BASE = `${GATEWAY_BASE}/setapiwrite`

// 调试信息
console.log('=== API 配置调试信息 ===')
console.log('isDev:', isDev)
console.log('GATEWAY_BASE:', GATEWAY_BASE)
console.log('FEE_READ_BASE:', FEE_READ_BASE)
console.log('FEE_WRITE_BASE:', FEE_WRITE_BASE)
console.log('PAYMENT_READ_BASE:', PAYMENT_READ_BASE)
console.log('PAYMENT_WRITE_BASE:', PAYMENT_WRITE_BASE)
console.log('VITE_FEE_READ_BASE_URL:', (import.meta as any)?.env?.VITE_FEE_READ_BASE_URL)
console.log('VITE_FEE_WRITE_BASE_URL:', (import.meta as any)?.env?.VITE_FEE_WRITE_BASE_URL)
console.log('VITE_GATEWAY_BASE_URL:', (import.meta as any)?.env?.VITE_GATEWAY_BASE_URL)
console.log('所有环境变量:', import.meta.env)
console.log('=== 强制配置确认 ===')
console.log('FEE_WRITE_BASE 应该是: http://115.190.179.32:8000/setapiwrite')
console.log('实际 FEE_WRITE_BASE:', FEE_WRITE_BASE)

// 审批流相关API（读/写）
export const examineApi = {
  // ==================== 读端（ExamineApi.Read） ====================
  // 付款审批列表查询（POST + QueryString）
  getPaymentApprovalList(params: any) {
    return http.post(`${EXAMINE_READ_BASE}/ExamineRead/PaymentApprovalList`, null, { params })
  },

  // 审批详细信息查询（POST + QueryString）
  getApprovalInfo(params: any) {
    return http.post(`${EXAMINE_READ_BASE}/ExamineRead/ApprovalInfo`, null, { params })
  },

  // 本轮已转批审批人ID列表（POST + QueryString）
  getTransferredApproverList(params: any) {
    return http.post(`${EXAMINE_READ_BASE}/ExamineRead/TransferredApproverList`, null, { params })
  },

  // 流程详情列表查询（POST + QueryString）
  getProcessDetailList(params: any) {
    return http.post(`${EXAMINE_READ_BASE}/ExamineRead/ProcessDetailList`, null, { params })
  },

  // 节点列表显示（GET + QueryString）
  getNodes(params: any) {
    return http.get(`${EXAMINE_READ_BASE}/Examine/NodesShow`, { params })
  },

  // 流程列表显示（GET + QueryString）
  getProcesses(params: any) {
    return http.get(`${EXAMINE_READ_BASE}/Examine/ProcessShow`, { params })
  },

  // 流程详情预设列表显示（GET + QueryString）
  getDefaultProcessDetails(params: any) {
    return http.get(`${EXAMINE_READ_BASE}/Examine/DefaultProcessDetailShow`, { params })
  },

  // 用户列表显示（POST + QueryString）
  getUsers(params: any) {
    return http.post(`${EXAMINE_READ_BASE}/ExamineRead/UsersList`, null, { params })
  },

  // 审批类型列表显示（POST + QueryString）
  getTypes(params: any) {
    // 直接调用8000端口完整URL，绕过代理和baseURL
    const url = 'http://115.190.179.32:8000/ExamineEngieRead/api/ExamineRead/TypeList'
    console.log('TypeList API调用URL:', url)
    console.log('TypeList API调用参数:', params)
    
    return axios.post(url, null, {
      headers: {
        'Content-Type': 'application/json'
      },
      params: params
    }).then(response => {
      console.log('TypeList API响应成功:', response)
      return response
    }).catch(error => {
      console.error('TypeList API调用失败:', error)
      throw error
    })
  },

  // ==================== 写端（ExamineApi.Write） ====================
  // 节点管理
  createNode(data: any) {
    return http.post(`${EXAMINE_WRITE_BASE}/ExamineEngie/CreateNode`, data)
  },
  updateNode(data: any) {
    return http.put(`${EXAMINE_WRITE_BASE}/ExamineEngie/UpdateNode`, data)
  },
  deleteNode(data: any) {
    return http.delete(`${EXAMINE_WRITE_BASE}/ExamineEngie/DeleteNode`, { data })
  },

  // 流程管理
  createProcess(data: any) {
    return http.post(`${EXAMINE_WRITE_BASE}/ExamineEngie/CreateProcess`, data)
  },
  updateProcess(data: any) {
    return http.put(`${EXAMINE_WRITE_BASE}/ExamineEngie/UpdateProcess`, data)
  },
  deleteProcess(data: any) {
    return http.delete(`${EXAMINE_WRITE_BASE}/ExamineEngie/DeleteProcess`, { data })
  },

  // 类型管理
  createType(data: any) {
    return http.post(`${EXAMINE_WRITE_BASE}/ExamineEngie/CreateType`, data)
  },
  updateType(data: any) {
    return http.put(`${EXAMINE_WRITE_BASE}/ExamineEngie/UpdateType`, data)
  },
  deleteType(data: any) {
    return http.delete(`${EXAMINE_WRITE_BASE}/ExamineEngie/DeleteType`, { data })
  },

  // 流程预设管理
  saveDefaultProcessDetails(data: any) {
    return http.post(`${EXAMINE_WRITE_BASE}/ExamineEngie/SaveDefaultProcessDetails`, data)
  },

  // 流程详情管理
  createFirstProcessDetail(data: any) {
    // 直接调用8000端口完整URL，绕过代理和baseURL
    const url = 'http://115.190.179.32:8000/ExamineEngieWrite/api/ExamineEngie/CreateFirstProcessDetail'
    console.log('ExamineAPI调用URL:', url)
    console.log('ExamineAPI调用数据:', data)
    
    return axios.post(url, data, {
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(response => {
      console.log('ExamineAPI响应成功:', response)
      return response
    }).catch(error => {
      console.error('ExamineAPI调用失败:', error)
      throw error
    })
  },
  submitProcessDetail(data: any) {
    return http.post(`${EXAMINE_WRITE_BASE}/ExamineEngie/SubmitProcessDetail`, data)
  },

  // ============== 审批预测（训练/追加/预测） ==============
  // 在线追加最新天数到 latest（Write）
  approvalForecastAppend(data: { typeCode: string }) {
    return http.post(`${EXAMINE_WRITE_BASE}/ExamineEngie/ApprovalForecastAppend`, data)
  },
  // 如需首训（Write）
  approvalForecastTrain(data: { typeCode: string }) {
    return http.post(`${EXAMINE_WRITE_BASE}/ExamineEngie/ApprovalForecastTrain`, data)
  },
  // 预测未来7天（Read）
  approvalForecastPredict(data: { typeCode: string }) {
    return http.post(`${EXAMINE_READ_BASE}/Examine/ApprovalForecastPredict`, data)
  }
}

// AI（Dify）相关 API（直接走读端 ExamineApi.Read）
export const aiApi = {
  // 流式聊天（SSE）。返回 { controller, reader }，调用方自行读取并解析。
  chatStream(data: { message: string; conversationId?: string | null; userId?: string; inputs?: any }) {
    const controller = new AbortController()
    const url = `${EXAMINE_READ_BASE}/api/Ai/chat/stream`
    const resp = fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        message: data.message,
        conversationId: data.conversationId ?? null,
        userId: data.userId ?? 'web-user',
        inputs: data.inputs ?? {}
      }),
      signal: controller.signal
    })
    return { controller, resp }
  },

  // 非流式（备用）
  async chat(data: { message: string; conversationId?: string | null; userId?: string; inputs?: any }) {
    const url = `${EXAMINE_READ_BASE}/api/Ai/chat`
    const r = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        message: data.message,
        conversationId: data.conversationId ?? null,
        userId: data.userId ?? 'web-user',
        inputs: data.inputs ?? {}
      })
    })
    return r.json()
  }
}

// 车辆服务管理 API（CarServicesApi.Read）
export const carServicesApi = {
  // 费用记录列表
  getFeeRecordList(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/FeeRecordShow`, { params })
  },
  // 费用记录详情（若有）
  getFeeRecordDetail(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/FeeRecordDetail`, { params })
  },

  // ============== AccidentRecord 事故记录（读） ==============
  getAccidentRecordList(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/AccidentRecordShow`, { params })
  },
  getAccidentRecordDetail(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/AccidentRecordDetail`, { params })
  },

  // ============== BreakRulesAndRegulations 违章记录（读） ==============
  getBreakRulesList(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/BreakRulesAndRegulationsShow`, { params })
  },
  getBreakRulesDetail(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/BreakRulesAndRegulationsDetail`, { params })
  },

  // ============== MaintainRecord 保养记录（读） ==============
  getMaintainRecordList(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/MaintainRecordShow`, { params })
  },
  getMaintainRecordDetail(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/MaintainRecordDetail`, { params })
  },

  // ============== RepairRecord 维修记录（读） ==============
  getRepairRecordList(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/RepairRecordShow`, { params })
  },
  getRepairRecordDetail(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/RepairRecordDetail`, { params })
  },

  // ============== TireRecord 轮胎记录（读） ==============
  getTireRecordList(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/TireRecordShow`, { params })
  },
  getTireRecordDetail(params: any) {
    return http.get(`${CARSERV_READ_BASE}/CarServices/TireRecordDetail`, { params })
  },

  // ============== FeeRecord 费用记录（写） ==============
  createFeeRecord(data: any) {
    return http.post(`${CARSERV_WRITE_BASE}/CarServices/FeeRecordCreate`, data)
  },
  updateFeeRecord(data: any) {
    return http.put(`${CARSERV_WRITE_BASE}/CarServices/FeeRecordUpdate`, data)
  },
  deleteFeeRecord(data: any) {
    return http.delete(`${CARSERV_WRITE_BASE}/CarServices/FeeRecordDelete`, { data })
  },

  // ============== AccidentRecord 事故记录（写） ==============
  createAccidentRecord(data: any) {
    return http.post(`${CARSERV_WRITE_BASE}/CarServices/AccidentRecordCreate`, data)
  },
  updateAccidentRecord(data: any) {
    return http.put(`${CARSERV_WRITE_BASE}/CarServices/AccidentRecordUpdate`, data)
  },
  deleteAccidentRecord(data: any) {
    return http.delete(`${CARSERV_WRITE_BASE}/CarServices/AccidentRecordDelete`, { data })
  },

  // ============== BreakRulesAndRegulations 违章记录（写） ==============
  createBreakRules(data: any) {
    return http.post(`${CARSERV_WRITE_BASE}/CarServices/BreakRulesAndRegulationsCreate`, data)
  },
  updateBreakRules(data: any) {
    return http.put(`${CARSERV_WRITE_BASE}/CarServices/BreakRulesAndRegulationsUpdate`, data)
  },
  deleteBreakRules(data: any) {
    return http.delete(`${CARSERV_WRITE_BASE}/CarServices/BreakRulesAndRegulationsDelete`, { data })
  },

  // ============== MaintainRecord 保养记录（写） ==============
  createMaintainRecord(data: any) {
    return http.post(`${CARSERV_WRITE_BASE}/CarServices/MaintainRecordCreate`, data)
  },
  updateMaintainRecord(data: any) {
    return http.put(`${CARSERV_WRITE_BASE}/CarServices/MaintainRecordUpdate`, data)
  },
  deleteMaintainRecord(data: any) {
    return http.delete(`${CARSERV_WRITE_BASE}/CarServices/MaintainRecordDelete`, { data })
  },

  // ============== RepairRecord 维修记录（写） ==============
  createRepairRecord(data: any) {
    return http.post(`${CARSERV_WRITE_BASE}/CarServices/RepairRecordCreate`, data)
  },
  updateRepairRecord(data: any) {
    return http.put(`${CARSERV_WRITE_BASE}/CarServices/RepairRecordUpdate`, data)
  },
  deleteRepairRecord(data: any) {
    return http.delete(`${CARSERV_WRITE_BASE}/CarServices/RepairRecordDelete`, { data })
  },

  // ============== TireRecord 轮胎记录（写） ==============
  createTireRecord(data: any) {
    return http.post(`${CARSERV_WRITE_BASE}/CarServices/TireRecordCreate`, data)
  },
  updateTireRecord(data: any) {
    return http.put(`${CARSERV_WRITE_BASE}/CarServices/TireRecordUpdate`, data)
  },
  deleteTireRecord(data: any) {
    return http.delete(`${CARSERV_WRITE_BASE}/CarServices/TireRecordDelete`, { data })
  }
}

// 基础信息 - 车辆管理 API
export const vehicleBasicApi = {
  // 列表（Read）
  getList(params: any) {
    return http.get(`${BASICINFO_READ_BASE}/VehicleManagement/GetVehicleList`, { params })
  },
  // 详情（Read）
  getById(id: number) {
    return http.get(`${BASICINFO_READ_BASE}/VehicleManagement/GetVehicleById/${encodeURIComponent(String(id))}`)
  },
  // 新增（Write）
  create(data: any) {
    return http.post(`${BASICINFO_WRITE_BASE}/VehicleManagement/Create`, data)
  },
  // 更新（Write）
  update(data: any) {
    return http.post(`${BASICINFO_WRITE_BASE}/VehicleManagement/Update`, data)
  },
  // 删除（Write）
  delete(data: any) {
    return http.post(`${BASICINFO_WRITE_BASE}/VehicleManagement/Delete`, data)
  },
  // 批量删除（Write）
  batchDelete(data: any) {
    return http.post(`${BASICINFO_WRITE_BASE}/VehicleManagement/BatchDelete`, data)
  }
}

// 物资管理API
export const materialApi = {
  // ================== 物资领用管理相关 ==================
  // 获取物资领用分页列表
  getPagedMaterialWithdrawal(params: any) {
    return http.get('http://115.190.179.32:8000/mateapiread/api/MaterialWithdrawal/GetPagedMaterialWithdrawal', { params })
  },
  
  // 获取物资领用详情
  getMaterialWithdrawalDetail(id: number) {
    return http.get(`http://115.190.179.32:8000/mateapiread/api/MaterialWithdrawal/GetDetail/${id}`)
  },
  
  // 删除单个物资领用记录
  deleteMaterialWithdrawal(id: number) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/MaterialWithdrawal/DeleteMaterialWithdrawal', { id })
  },
  
  // 批量删除物资领用记录
  deleteListMaterialWithdrawal(ids: number[]) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/MaterialWithdrawal/DeleteListMaterialWithdrawal', { ids })
  },
  
  // 提交审批
  submitMaterialWithdrawalApproval(id: number) {
    return http.post(`http://115.190.179.32:8000/mateapiread/api/MaterialWithdrawal/submitApproval/${id}`, {})
  },
  
  // 撤回审批
  cancelMaterialWithdrawalApproval(id: number) {
    return http.post(`http://115.190.179.32:8000/mateapiread/api/MaterialWithdrawal/cancelApproval/${id}`, {})
  },

  // ================== 物资采购管理相关 ==================
  // 获取物资采购分页列表
  getSupplyPurchaseList(params: any) {
    return http.get('http://115.190.179.32:8000/mateapiread/api/SupplyPurchase/query', { params })
  },
  
  // 删除单个物资采购记录
  deleteSupplyPurchase(id: number) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/SupplyPurchase/DeleteSupplyPurchase', { id })
  },
  
  // 批量删除物资采购记录
  deleteListSupplyPurchase(ids: number[]) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/SupplyPurchase/DeleteListSupplyPurchase', { ids })
  },

  // ================== 物资统计相关 ==================
  // 获取物资统计数据
  getMaterialStatistics(params: any) {
    return http.get('http://115.190.179.32:8000/mateapiread/api/MaterialStatistics/show', { params })
  },

  // ================== 仓库收货管理相关 ==================
  // 获取仓库收货分页列表
  getWarehouseReceivingList(params: any) {
    return http.get('http://115.190.179.32:8000/mateapiread/api/WarehouseReceiving/GetWarehouseReceivingList', { params })
  },
  
  // 删除仓库收货记录
  deleteWarehouseReceivingManagement(swNo: string) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/WarehouseReceiving/DeleteWarehouseReceivingManagement', { swNo })
  },
  
  // 批量删除仓库收货记录
  deleteListWarehouseReceivingManagement(swNos: string[]) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/WarehouseReceiving/DeleteLsitWarehouseReceivingManagement', { swNos })
  },

  // ================== 通用材质管理 ==================
  // 获取材质列表
  getMaterials() {
    return http.get('http://115.190.179.32:8000/mateapiread/api/WarehouseReceiving/GetMaterials')
  },

  // ================== 物资领用管理新增/更新 ==================
  // 新增物资领用
  addMaterialWithdrawal(data: any) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/MaterialWithdrawal/AddMaterialWithdrawal', data)
  },

  // 更新物资领用
  updateMaterialWithdrawal(data: any) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/MaterialWithdrawal/UpdateMaterialWithdrawal', data)
  },

  // ================== 物资采购管理新增/更新/详情 ==================
  // 新增物资采购
  addSupplyPurchase(data: any) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/SupplyPurchase/AddSupplyPurchase', data)
  },

  // 更新物资采购
  updateSupplyPurchase(data: any) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/SupplyPurchase/UpdateSupplyPurchase', data)
  },

  // 获取物资采购详情
  getSupplyPurchaseDetail(id: number) {
    return http.get(`http://115.190.179.32:8000/mateapiread/api/SupplyPurchase/details/${id}`)
  },

  // ================== 仓库收货管理新增/更新/详情 ==================
  // 获取类型列表
  getTypes() {
    return http.get('http://115.190.179.32:8000/mateapiread/api/WarehouseReceiving/GetTypes')
  },

  // 新增仓库收货
  addWarehouseReceivingManagement(data: any) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/WarehouseReceiving/AddWarehouseReceivingManagement', data)
  },

  // 更新仓库收货
  updateWarehouseReceivingManagement(data: any) {
    return http.post('http://115.190.179.32:8000/mateapiwrite/api/WarehouseReceiving/UpdateWarehouseReceivingManagement', data)
  },

  // 获取仓库收货详情
  getWarehouseReceivingDetail(swNo: string) {
    return http.get(`http://115.190.179.32:8000/mateapiread/api/WarehouseReceiving/GetDetails?swNo=${swNo}`)
  }
}

// 合同追踪服务地址配置（使用统一网关地址）
const TRACKING_READ_BASE = ORDER_READ_BASE
const TRACKING_WRITE_BASE = ORDER_WRITE_BASE

// 合同追踪管理 API
export const contractTrackingApi = {
  // ==================== 读端接口（查询服务） ====================
  
  // 获取合同追踪列表
  getContractTrackingList(params: import('@/types/api').ContractTrackingListParams) {
    return http.get<import('@/types/api').ContractTrackingListResponse>(
      `${TRACKING_READ_BASE}/api/ContractTracking/list`, 
      { params }
    )
  },

  // 获取合同追踪详情
  getContractTrackingDetail(contractId: number, contractType?: string) {
    return http.get<import('@/types/api').ContractTrackingDetail>(
      `${TRACKING_READ_BASE}/api/ContractTracking/detail/${contractId}`, 
      { params: { contractType: contractType || '货主合同' } }
    )
  },

  // 获取合同的车辆实时位置
  getVehicleLocations(contractId: number, contractType?: string) {
    return http.get<import('@/types/api').VehicleLocation[]>(
      `${TRACKING_READ_BASE}/api/ContractTracking/vehicle-locations/${contractId}`, 
      { params: { contractType: contractType || '货主合同' } }
    )
  },

  // 获取合同的追踪日志
  getTrackingLogs(contractId: number, contractType?: string) {
    return http.get<import('@/types/api').TrackingLog[]>(
      `${TRACKING_READ_BASE}/api/ContractTracking/tracking-logs/${contractId}`, 
      { params: { contractType } }
    )
  },

  // 获取合同的到站记录
  getStationRecords(contractId: number, contractType?: string) {
    return http.get<import('@/types/api').StationRecord[]>(
      `${TRACKING_READ_BASE}/api/ContractTracking/station-records/${contractId}`, 
      { params: { contractType } }
    )
  },

  // ==================== 写端接口（写入服务） ====================
  
  // 添加追踪日志
  addTrackingLog(data: import('@/types/api').AddTrackingLogParams) {
    return http.post<number>(
      `${TRACKING_WRITE_BASE}/api/TrackingLog`, 
      data
    )
  },

  // 批量添加追踪日志
  batchAddTrackingLog(data: import('@/types/api').BatchAddTrackingLogParams) {
    return http.post<number>(
      `${TRACKING_WRITE_BASE}/api/TrackingLog/batch`, 
      data
    )
  },

  // 生成模拟追踪数据（测试用）
  generateMockData(contractId: number, licensePlateNumber?: string) {
    return http.post<number>(
      `${TRACKING_WRITE_BASE}/api/TrackingLog/generate-mock/${contractId}`, 
      null,
      { params: { licensePlateNumber: licensePlateNumber || '京A12345' } }
    )
  }
}

// 下方存在完全重复的 materialApi / TRACKING_* / contractTrackingApi 定义，已移除重复块，以上定义为唯一来源